﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.Xml;

namespace Mozlite.Configuration
{
    /// <summary>
    /// 数据库提供者。
    /// </summary>
    public class DataProvider
    {
        private Dictionary<string, Provider> providers = new Dictionary<string, Provider>(StringComparer.OrdinalIgnoreCase);

        internal DataProvider(XmlNode root)
        {
            this.Attributes = new NameValueCollection(StringComparer.OrdinalIgnoreCase);
            foreach (XmlAttribute attr in root.Attributes)
            {
                this.Attributes.Add(attr.Name, attr.Value);
            }
            foreach (XmlNode node in root)
            {
                if (node.NodeType != XmlNodeType.Comment)
                {
                    switch (node.Name)
                    {
                        case "add":
                            providers.Add(node.GetAttribute("name", null), new Provider(node.Attributes, this.Attributes["owner"], this.Attributes["profix"], this.Attributes["connectionString"]));
                            break;
                        case "remove":
                            providers.Remove(node.GetAttribute("name", null));
                            break;
                        case "clear":
                            providers.Clear();
                            break;
                    }
                }
            }
        }
        /// <summary>
        /// 数据库提供者的属性名称。
        /// </summary>
        public NameValueCollection Attributes { get; private set; }
        /// <summary>
        /// 获取数据库提供者对象。
        /// </summary>
        /// <param name="name">数据库提供者类名称。</param>
        /// <returns>返回数据库提供者对象。</returns>
        public Provider this[string name]
        {
            get
            {
                Provider provider;
                if (providers.TryGetValue(name, out provider))
                    return provider;
                return null;
            }
        }
    }
}
